const mixin = require('../../../mixins');

const {
	globalData
} = getApp();
Component({
	behaviors: [mixin],
	data: {
		currIndex: 0,
		cornerMarkerObj: {
			left: [],
			right: []
		},
		bottomHeight: 'calc( 100vh - 120rpx )',
		autoPlay: false,
		animePlaying: false,
		userTouchStatus: false,
		trackingParams: null,
		utoolsShopLists: [],
		start: false,
		timer: null,
	},
	properties: {
		mf_data: Object,
	},
	pageLifetimes: {
		show: function() {
			this.setData({
				['mf_data.autoPlay']: true
			})
		},
		hide: function() {
			this.setData({
				['mf_data.autoPlay']: false
			})
		},
	},
	attached() {

		this.initCornerMarker();
		this.setData({
			bottomHeight: globalData.isIpx ? 'calc( 100vh - 150rpx )' : 'calc( 100vh - 120rpx )'
		}, () => {
			
		})
	},
	async ready() {
		try {
			if (this.data.mf_data && this.data.mf_data.label1 == '首屏swiper') {
				this.data.autoPlay = this.data.mf_data.autoPlay || false
				this.setData({
					['mf_data.autoPlay']: false
				})
				globalData.event.on('swiperAutoPlay', this.swiperAutoPlay, this)
			}
			//  轮训查询当前轮播子集是否包含商品列表
			await this.filterUtoolsShopLists(this.data.mf_data, 'type', 'commodityList');

		} catch (e) {}
	},
	methods: {

		stspEvent(e) {
			if(this.data.autoPlay) {
				// console.log('接收到子组件传递的数据：', e);
				if(e.detail) {
					this.setData({['mf_data.autoPlay']: true},this.navigationRight)
				}else {
					this.setData({['mf_data.autoPlay']: false})
				}
			}
		},
		handleTouchStart(e) {
			this.flag = 0;
			this.lastX = e.changedTouches[0].pageX;
			this.lastY = e.changedTouches[0].pageY;
		},
		handleTouchEnd(e) {
			//停止滑动
			this.flag = 0;
		},
		handleTouchMove(e) {
			try {
				if (this.flag !== 0) return;
				let currentX = e.changedTouches[0].pageX;
				let currentY = e.changedTouches[0].pageY;
				let tx = currentX - this.lastX;
				let ty = currentY - this.lastY;

				let index = this.data.currIndex;
				// 向左滑动
				if (tx < 0) {
					// 如果到最右侧
					if (this.data.currIndex >= this.data.mf_data.children.length - 1) {
						index = 0;
					} else {
						index = this.data.currIndex + 1;
					}
					this.flag = 1;
					// 向右滑动（）
				} else if (tx > 0) {
					// 如果到最左侧
					if (this.data.currIndex <= 0) {
						index = this.data.mf_data.children.length - 1;
					} else {
						index = this.data.currIndex - 1;
					}
					this.flag = 2;
				}
				//  触发神策埋点
				this.touchSwiperTrack(index);
				//将当前坐标进行保存以进行下一次计算
				this.lastX = currentX;
				this.lastY = currentY;
			} catch (e) {}
		},
		//注册的事件
		swiperAutoPlay() {
			if (this.data.autoPlay) {
				this.setData({
					start: true,
					['mf_data.autoPlay']: true
				})
			}
		},

		initCornerMarker() {
			const {
				cornerMarker,
				children
			} = this.properties.mf_data;
			if (!cornerMarker) return;
			const {
				currIndex
			} = this.data;
			this.setData({
				cornerMarkerObj: {
					left: String(currIndex + 1).split(""),
					right: String(children.length).split(""),
				}
			})
		},
		onChange(event) {
			const {
				current,
				isChanging
			} = event.detail;
			// if (!isChanging) {
			this.data.timer && clearTimeout(this.data.timer), this.data.timer = null;
			this.data.animePlaying = true;
			this.data.timer = setTimeout(() => {
				this.setData({
				['mf_data.autoPlay']: true,
					currIndex: current
				}, () => {
					this.initCornerMarker();
				})
				clearTimeout(this.data.timer), this.data.timer = null;
			}, 500)

			// }
		},
		//  筛选utools json中的商品列表对象
		async filterUtoolsShopLists(data, key, value) {
			try {
				if (data && data[key] && data[key] === value) {
					this.data.utoolsShopLists.push(data)
					return true;
				}
				if (data && data.children && data.children.length) {
					for (let i = 0; i < data.children.length; i++) {
						if (data.children[i]) {
							this.filterUtoolsShopLists(data.children[i], key, value);
						}
					}
				}
				return false;
			} catch (e) {}
		},
		//  轮播神策埋点
		touchSwiperTrack(index) {
			try {
				if (!this.flag) return;
				//  首页神策埋点 首页轮播/系列甄选
				if (this.data.mf_data && (this.data.mf_data.label1 == '首屏swiper' || this.data.mf_data.label1 == '系列甄选')) {
					const _tag = this.data.mf_data.children[index];
					const res = _tag.children.find(el => el.type === "hotSpace");
					if (res && res.trackingParams) {
						let _trackData = JSON.parse(res.trackingParams);
						_trackData.name = "BannerExposure";
						_trackData.type = "view";
						this.triggerEvent('triggerComponent', {
							data: {
								trackData: JSON.stringify(_trackData),
								type: "track"
							}
						}, {
							bubbles: true,
							composed: true
						});
						return;
					}
				}
				//  神策埋点-轮播嵌套线上精选模块
				if (this.data.utoolsShopLists && this.data.utoolsShopLists.length) {
					const _tag = this.data.utoolsShopLists[index] || null;
					return this.trackProductBannerExpo(_tag, index)
				}
				//  神策埋点
				this.findSwiperChildTrackData(index);
			} catch (e) {}
		},
		//  线上精选神策埋点
		trackProductBannerExpo(datas) {
			try {
				if (datas && datas.children && datas.trackingParams) {
					let _trackData = JSON.parse(datas.trackingParams);
					if (_trackData.name && _trackData.data) {
						const page = getCurrentPages();
						//  获取父级商品列表
						let {
							utoolsClassGoodsLists
						} = page[page.length - 1].data;
						let list = utoolsClassGoodsLists;
						let product_sku_list = [];
						let product_name_list = [];
						datas.children.forEach(item => {
							let goods = list.filter(it => it.itemId == item.itemId)[0];
							if (goods) {
								if (goods.skuCodes && goods.skuCodes[0]) product_sku_list.push(goods.skuCodes[0]);
								if (goods.itemName) product_name_list.push(goods.itemName);
							}
						})
						if (product_sku_list.length && product_name_list.length) {
							_trackData.data.product_sku_list = product_sku_list;
							_trackData.data.product_name_list = product_name_list;
							this.triggerEvent('triggerComponent', {
								data: {
									trackData: JSON.stringify(_trackData),
									type: "track"
								}
							}, {
								bubbles: true,
								composed: true
							});
						}
					}
				}
			} catch (e) {}
		},
		//  查找轮播子集对应埋点内容-并发送
		async findSwiperChildTrackData(index) {
			const _child = this.data.mf_data.children[index] || null;
			const _track = await this.filterUtoolsByKey(_child, 'trackingParams');
			if (_track) {
				this.triggerEvent('triggerComponent', {
					data: {
						trackData: _track,
						type: "track"
					}
				}, {
					bubbles: true,
					composed: true
				});
			}
		},
		async filterUtoolsByKey(data, key) {
			try {
				if (data && data[key]) return data[key];
				if (data && data.children && data.children.length) {
					for (let i = 0; i < data.children.length; i++) {
						if (this.filterUtoolsByKey(data.children[i], key)) {
							return this.filterUtoolsByKey(data.children[i], key);
						}
					}
				}
				return null;
			} catch (e) {
				return null;
			}
		},
		onAnimationFinish(e) {
			this.data.animePlaying = false;
		},
		changeTo(_index) {
			this.onChange({
				detail: {
					current: _index
				}
			})
		},
		navigationRight() {
			let {
				currIndex
			} = this.data;
			let index = currIndex < (this.properties.mf_data.children.length - 1) ? currIndex + 1 : 0;
			this.changeTo(index)
		},
		navigationLeft() {
			let {
				currIndex
			} = this.data;
			let index = currIndex > 0 ? currIndex - 1 : this.properties.mf_data.children.length - 1;
			this.changeTo(index)
		},
		OnCurrentChange(e) {
			const {
				detail: {
					currIndex
				}
			} = e
			this.setData({
				currIndex
			})
		}
	},
});